package com.hnevc.getpostnetdemo;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class MainActivity extends AppCompatActivity {

    //public static final String BaseURL = "http://10.1.46.91:8080/Restaurant";
    public static final String BaseURL = "http://10.1.46.115:8080/RestaurantServer";
    public static final String TAG = "TEST";
    public static final int WHAT = 101;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == WHAT) {
                if (msg.arg1 == 1) {
                    Toast.makeText(MainActivity.this, msg.obj + "登陆成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "登陆失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



    }

    public void loginClick(View v) {
        switch (v.getId()) {
            case R.id.id_btn_show_foodlist:{
                Intent intent = new Intent(MainActivity.this, FoodListActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.id_btn_post_json: {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        loginJson();
                    }
                }).start();

                break;
            }
            case R.id.id_btn_post_form:{
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        loginPostForm();
                    }
                }).start();

                break;
            }
            case R.id.id_btn_get_form:{
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        loginGetForm();
                    }
                }).start();

                break;
            }

        }
    }

    private void loginJson() {

        try {
            String loginUrl = "/user/doLogin";
            URL url = new URL(BaseURL + loginUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);

            //设置提交方式
            conn.setRequestMethod("POST");

            //准备数据，设置相应的属性

            //设置提交的数据内容类型
            //json格式
            conn.setRequestProperty("Content-Type", "application/json");
            JSONObject obj = new JSONObject();
            obj.put("userName", "tom");
            obj.put("userPassword", "123");
            String data = obj.toString();
            //设置提交的数据的长度
            conn.setRequestProperty("Content-Length", data.length() + "");


            //POST请求
            OutputStream out = conn.getOutputStream();
            out.write(data.getBytes("utf-8"));
            out.flush();
            out.close();

            int code = conn.getResponseCode();
            if (code == 200) {

                BufferedReader reader
                        = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String lines;
                StringBuffer sb = new StringBuffer();
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes(), "utf-8");
                    sb.append(lines);
                }
                String returnData = sb.toString();

                Message msg = mHandler.obtainMessage();
                msg.what = WHAT;
                msg.arg1 = 1;
                msg.obj = returnData;
                mHandler.sendMessage(msg);
            } else {
                Message msg = mHandler.obtainMessage();
                msg.what = WHAT;
                msg.arg1 = 0;

                mHandler.sendMessage(msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void loginPostForm() {

        try {
            String loginUrl = "/user/doLogin2";
            URL url = new URL(BaseURL + loginUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);

            //设置提交方式
            conn.setRequestMethod("POST");

            //准备数据，设置相应的属性
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            String data = ("userName=" + URLEncoder.encode("李白", "utf-8") + "&userPassword=123");
            conn.setRequestProperty("Content-Length", data.length() + "");

            //POST请求
            OutputStream out = conn.getOutputStream();
            out.write(data.getBytes("utf-8"));
            out.flush();
            out.close();

            int code = conn.getResponseCode();
            if (code == 200) {

                BufferedReader reader
                        = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String lines;
                StringBuffer sb = new StringBuffer();
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes(), "utf-8");
                    sb.append(lines);
                }
                String returnData = sb.toString();

                Message msg = mHandler.obtainMessage();
                msg.what = WHAT;
                msg.arg1 = 1;
                msg.obj = returnData;
                mHandler.sendMessage(msg);
            } else {
                Message msg = mHandler.obtainMessage();
                msg.what = WHAT;
                msg.arg1 = 0;

                mHandler.sendMessage(msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void loginGetForm() {

        try {
            String loginUrl = "/user/doLogin3";
            URL url = new URL(BaseURL + loginUrl+"?userName="
                    +URLEncoder.encode("李白","utf-8")
                    +"&userPassword="+URLEncoder.encode("123"));
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            //设置提交方式
            conn.setRequestMethod("GET");
            int code = conn.getResponseCode();
            if (code == 200) {

                BufferedReader reader
                        = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String lines;
                StringBuffer sb = new StringBuffer();
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes(), "utf-8");
                    sb.append(lines);
                }
                String returnData = sb.toString();

                Message msg = mHandler.obtainMessage();
                msg.what = WHAT;
                msg.arg1 = 1;
                msg.obj = returnData;
                mHandler.sendMessage(msg);
            } else {
                Message msg = mHandler.obtainMessage();
                msg.what = WHAT;
                msg.arg1 = 0;

                mHandler.sendMessage(msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
